package utils

import (
	"context"
	"git.mycaigou.com/gfyx/common/cache"
	"strconv"
)

const (
	CompanyIdToTenantCodeKey = "gfyx:byai:company2tenant"
	TenantCodeToCompanyIdKey = "gfyx:byai:tenant2company"
)

func SetByRelation(ctx context.Context, tenantCode string, companyId, oldCompanyId int64) (bool, error) {
	redisClient, _ := cache.Redis()
	_, err := redisClient.HSet(ctx, CompanyIdToTenantCodeKey, companyId, tenantCode)
	if err != nil {
		return false, err
	}
	_, err = redisClient.HSet(ctx, TenantCodeToCompanyIdKey, tenantCode, companyId)
	if err != nil {
		return false, err
	}
	if oldCompanyId > 0 {
		_, err = redisClient.HDel(ctx, CompanyIdToTenantCodeKey, oldCompanyId)
		if err != nil {
			return false, err
		}
	}
	return true, nil
}

func GetByCompanyId(ctx context.Context, tenantCode string) (int64, error) {
	redisClient, _ := cache.Redis()
	value, err := redisClient.HGet(ctx, TenantCodeToCompanyIdKey, tenantCode)
	if err != nil {
		return 0, err
	}
	companyId, err := strconv.ParseInt(value, 10, 64)
	if err != nil {
		return 0, err
	} else {
		return companyId, nil
	}
}

func GetTenantCodeForBy(ctx context.Context, companyId int64) (string, error) {
	redisClient, _ := cache.Redis()
	tenantCode, err := redisClient.HGet(ctx, CompanyIdToTenantCodeKey, companyId)
	if err != nil {
		return "", err
	}
	return tenantCode, nil
}

func GetAllTenantCode(ctx context.Context) ([]string, error) {
	redisClient, _ := cache.Redis()
	resp, err := redisClient.HGetAll(ctx, TenantCodeToCompanyIdKey)
	if err != nil {
		return nil, err
	}
	var tenantCodeList []string
	for k, _ := range resp {
		tenantCodeList = append(tenantCodeList, k)
	}
	return tenantCodeList, nil
}
